< previous page page_187 next page >

Page 187
Searching a String
For many string-related tasks, the first programming requirement is to determine whether a word, phrase, or other group of characters exists in a string and, if so, where. The capability to find one string within another enables you to perform word searches within text. You can do these searches to perform a global replacement of a string, such as replacing the word text with the word string throughout a word processing document.
Another, more common, reason for searching within a string is parsing the string. For example, suppose you have an input string that contains a person's name in this format: ''Dr. Stirling P. Williams, Jr." If you have a file of a hundred such strings, putting this information into a database with separate first and last name fields would be a little difficult. However, you can use a string search function along with a little program logic to parse the string into smaller pieces.
The function that enables you to search a string for a character or group of characters is the InStr function. This function has two required and two optional parameters. The required parameters are the string to be searched and the text to search for. If the search text appears in the string being searched, InStr returns the index of the character where the search string starts. If the search text is not present, InStr returns 0. The simple syntax of the InStr function is shown here:
chrpos = InStr(sourcestr, searchstr)
For example, the function call
Print Instr("I'll see you next Tuesday.","you")
prints a result of 10 because that is the position where the word you begins.
The first optional parameter of the InStr function tells the function the character position from which to start the search. This position must be a positive integer. If the starting position is greater than the length of the string, InStr returns 0. The syntax of the InStr function is as follows:
chrpos = InStr(StartPos, sourcestr, searchstr)
For example, the function call
Print Instr(7,"Pride cometh before a fall","e")
returns the value of 10, even though the first e in the string is at position 5, because the search starts from position 7.
The other optional parameter determines whether the search to be performed is case-sensitive (uppercase and lowercase letters do not match) or not case-sensitive. Setting the value of the comparison parameter to 0, its default value, performs a case-sensitive search. Setting the value to 1 performs a search that is not case-sensitive. This syntax is shown here:
chrpos = InStr(StartPos, sourcestr, searchstr, 1)
Note that with the optional parameters, you can write code that finds each successive search string in your text. The code in Listing 9.4 prints the words in a string that are separated by spaces. It works by taking the result of the Instr function and passing it back in to the StartPos parameter.

 
< previous page page_187 next page >